package com.initial.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.initial.entity.TbCrmEmployee;
import com.initial.entity.TbSystemUser;
import com.initial.mapper.TbSystemUserMapper;
import com.initial.service.TbCrmEmployeeService;
import com.initial.service.TbCrmLoginHistoryService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class UserLogin {
    @Resource
    private TbSystemUserMapper userMapper;
    @Resource
    private TbCrmLoginHistoryService tbCrmLoginHistoryService;
    @Resource
    private TbCrmEmployeeService employeeService;
    //    用户信息验证
    @RequestMapping("/userLogin")
    @ResponseBody
    public ModelMap verify(TbSystemUser user, HttpSession session,HttpServletRequest request) {
        ModelMap map = new ModelMap();
        TbSystemUser tbSystemUser = userMapper.selectByName(user.getUsername(),user.getPassword());
        String loginStatus="1";
        if (tbSystemUser != null) {
            map.addAttribute("success", true);
            session.setAttribute("user", tbSystemUser);
//            将登录用户对应的的员工信息放到session中
            Integer userId = tbSystemUser.getId();
            QueryWrapper<TbCrmEmployee> queryWrapper=new QueryWrapper<TbCrmEmployee>();
            queryWrapper.eq("user_id",userId);
            TbCrmEmployee employee = employeeService.getOne(queryWrapper);
            session.setAttribute("employee",employee);
        }else {
            map.addAttribute("success", false);
            map.addAttribute("message", "用户名或密码错误");
            loginStatus="0";
        }
        int i = tbCrmLoginHistoryService.addUserIp(request, session, loginStatus);
        return map;
    }
    //    页面跳转
    @RequestMapping("/toIndex")
    public String toIndex() {
        //todo
        return "views/index";
    }



}
